package com.cat.gridChart;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/count-sub-islands/description/
 * @create 2025/9/6 22:35
 * @since JDK17
 */

public class Solution09 {
    int[][] g1, g2;
    int ans, n, m;

    int dfs(int x, int y) {
        if (x == -1 || x == n || y == -1 || y == m) {
            return 0;
        }
        if (g2[x][y] == 0) {
            return 0;
        }
        if (g2[x][y] == 1 && g1[x][y] != 1) {
            return -99999;
        }
        g2[x][y] = 0;
        int ans = 1;
        ans += dfs(x + 1, y) + dfs(x - 1, y) + dfs(x, y - 1) + dfs(x, y + 1);
        return ans;
    }

    public int countSubIslands(int[][] grid1, int[][] grid2) {
        n = grid1.length;
        m = grid1[0].length;
        g1 = grid1;
        g2 = grid2;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (g2[i][j] != 0) {
                    ans += Math.max(0, Math.min(1, dfs(i, j)));
                }
            }
        }

        return ans;
    }
}
